import axios from "axios";

const ajax = axios.create({
    baseURL: "http://localhost:8080",
    timeout: 10000,
});

ajax.interceptors.request.use(
    (config) => {
        let token = sessionStorage.getItem("token");

        if (token) {
            config.headers.Authorization = token;
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

ajax.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        let message = error.response.data.message;

        if (
            error.response.status === 401 &&
            (message == "无效签名" ||
                message == "签名过期" ||
                message == "forbidden")
        ) {
            alert("登录已过期，请重新登录");
            sessionStorage.removeItem("token");
            window.location.href = "/";
        }

        return Promise.reject(error);
    }
);

export default ajax;